package com.mes.web.controller.yzl;

import com.mes.entity.hpf.SalePlanDetail;
import com.mes.entity.hy.Product;
import com.mes.entity.tdd.Staff;
import com.mes.entity.yzl.*;
import com.mes.entity.yzlExtend.ExtendCustomerOrder;
import com.mes.entity.yzlExtend.ExtendProductor;
import com.mes.entity.zc.CustomerDetails;
import com.mes.service.hpf.CustomerDetailsService;
import com.mes.service.yzl.CustomerOrderService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/yzl")
public class CustomerOrderController {

    protected Logger logger = Logger.getLogger(CustomerOrderController.class);
    private static final long serialVersionUID = 8550329576989690578L;

    @Resource
    public CustomerOrderService customerOrderService;

    //销售计划单号生成并获取当前登录人
    @RequestMapping("/customerOrderNumLast")
    public @ResponseBody Map customerOrderNumLast(HttpSession session){

    	Map map = new HashMap();
        String returnNumber = "";
        returnNumber = customerOrderService.customerOrderNumLast();
        map.put("returnNumber", returnNumber);
        Staff staff = (Staff) session.getAttribute("staff");
        map.put("staff", staff);
        return map;

    }

    //条件分页查询
    @RequestMapping("/customerOrderList")
    public @ResponseBody ListBack customerOrderList(Condition condition){
    	DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ListBack listBack = new ListBack();

        //查询条件处理
        Sup sup = new Sup();
        condition = sup.tdSet(condition);
        int count = customerOrderService.countNew(condition);
        listBack.setTotal(count);
        List<CustomerOrder> customerOrders = new ArrayList<>();
        customerOrders = customerOrderService.listcustomerOrderNew(condition);
        listBack.setRows(customerOrders);
        return listBack;
    }

    //添加销售计划单
    @RequestMapping("/addFrom")
    public @ResponseBody int addFrom(@RequestBody Object obj) throws ParseException {
        int isSuccess = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = JSONObject.fromObject(obj);

        JSONArray jsonArray = jsonObject.getJSONArray("productors");

        //新增销售单
        CustomerOrder customerOrder = new CustomerOrder();
        customerOrder.setOrderNumber((String)jsonObject.get("number"));
        customerOrder.setCustomerId(Integer.valueOf((String)jsonObject.get("customerId")));
        customerOrder.setEntryPerson(Integer.valueOf((String)jsonObject.get("entryPerson")));
        customerOrder.setDemandDate((new java.sql.Date(simpleDateFormat.parse((String)jsonObject.get("planDate")).getTime())));
        customerOrder.setProduceStatus("0");
        customerOrder.setOutLibraryStatus("0");
        customerOrder.setOrderExamineStatus("0");
        customerOrder.setRemark("0");
        customerOrder.setIsSelect("0");
        int addIsSuccess = 0;
        try {
            addIsSuccess = customerOrderService.addCustomerOrder1(customerOrder,jsonArray);
        }catch (Exception e){
            addIsSuccess = 0;
        }
        return addIsSuccess;
    }

    //根据ID查询销售计划单
    @RequestMapping("/findOrderById")
    public @ResponseBody ExtendCustomerOrder findOrderById(long id){
        ExtendCustomerOrder extendCustomerOrder = new ExtendCustomerOrder();
        extendCustomerOrder = customerOrderService.findOrderById(id);
        return extendCustomerOrder;
    }


    //销售计划单详情
    @RequestMapping("/customerOrderXq")
    public @ResponseBody List<SalePlanDetail> customerOrderXq(long id){
        List<SalePlanDetail> salePlanDetails = new ArrayList<>();
        salePlanDetails = customerOrderService.customerOrderXq(id);
        return salePlanDetails;
    }

    //更新销售计划单
    @RequestMapping("/updateFrom")
    public @ResponseBody int updateFrom(@RequestBody Object obj) throws ParseException{
        int isSuccess = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = JSONObject.fromObject(obj);
        JSONArray jsonArray = jsonObject.getJSONArray("productors");

        CustomerOrder customerOrder = new CustomerOrder();
        customerOrder.setId(jsonObject.getLong("id"));
        customerOrder.setCustomerId(Integer.valueOf((String)jsonObject.get("customerId")));
        customerOrder.setEntryPerson(Integer.valueOf((String)jsonObject.get("entryPerson")));
        customerOrder.setDemandDate((new java.sql.Date(simpleDateFormat.parse((String)jsonObject.get("planDate")).getTime())));

        try {
            isSuccess = customerOrderService.updateCustomerAll(customerOrder,jsonArray);
        }catch (Exception e){
            isSuccess = 0;
        }

        return isSuccess;
    }

    //删除销售计划单 （需要事物处理  暂时没做）
    @RequestMapping("/deleteOrder")
    public @ResponseBody int deleteOrder(@RequestParam(value = "arr") String arr){

        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        for (int i = 0; i < list.size(); i++) {
        	//删除销售计划
            int deleteOrder = customerOrderService.deleteOrder(list.get(i));

            //循环删除对应的产品
            //首先根据销售计划单ID 查询出所有的产品
            if(deleteOrder > 0){
                //循环删除
            	customerOrderService.deletePlanDetial(list.get(i));
            }
            isSuccess = deleteOrder;
		}
        return isSuccess;
    }

    //需要用到的基础信息  列表查询 start

    //客户列表（没有分页）
    @RequestMapping("/customerList")
    public @ResponseBody List<Customer> customerList(){
        List<Customer> customers = new ArrayList<>();
        customers = customerOrderService.customerList();
        return customers;
    }

    //产品列表
    @RequestMapping("/carList")
    public @ResponseBody ListBack carList(Condition condition){
    	ListBack listBack = new ListBack();

        //查询条件处理
        Sup sup = new Sup();
        condition = sup.tdSet(condition);
        int count = customerOrderService.carCount();
        listBack.setTotal(count);
        List<Productor> productors = new ArrayList<>();
        productors = customerOrderService.carPageList(condition);
        listBack.setRows(productors);
        return listBack;
    }

    //需要用到的基础信息  列表查询 end


    //一下为修改状态的  审批流程 start

    //提交审核
    @RequestMapping("/orderApproveds")
    public @ResponseBody int orderApproveds(@RequestParam(value = "arr") String arr){

        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        isSuccess = customerOrderService.orderApproveds(list);
        return isSuccess;
    }

    //撤销审核
    @RequestMapping("/orderUnApproveds")
    public @ResponseBody int orderUnApproveds(@RequestParam(value = "arr") String arr){
        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        isSuccess = customerOrderService.orderUnApproveds(list);
        return isSuccess;
    }
    
    //导出
    @RequestMapping("/orderExport")
    public void orderExport(HttpServletResponse response) throws IOException{
        List<CustomerOrder> cusOrderList = customerOrderService.listALlCustomerOrde();
        String[] headers = { "序号", "计划单号", "计划日期", "客户", "生产状态", "出库状态", "审批状态" };
	 	//创建HSSFWorkbook对象(excel的文档对象)
	 	Workbook wb=new XSSFWorkbook();
	 	//建立新的sheet对象（excel的表单）
	 	Sheet sheet=wb.createSheet("销售计划表");
	 	// 设置表格默认列宽度
        sheet.setDefaultColumnWidth(100);
        
        // 产生表格标题行  
        Row row=sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {  
        	row.createCell(i).setCellValue(headers[i]);
        }
		for (int i = 0; i < cusOrderList.size(); i++) {
			Row row2=sheet.createRow(i+1);
			row2.createCell(0).setCellValue(i+1);
			row2.createCell(1).setCellValue(cusOrderList.get(i).getOrderNumber());
			row2.createCell(2).setCellValue(cusOrderList.get(i).getDemandDate().toString());
			row2.createCell(3).setCellValue(cusOrderList.get(i).getName());
			if (cusOrderList.get(i).getProduceStatus().equals("0")) {
				row2.createCell(4).setCellValue("未生产");
			} else if (cusOrderList.get(i).getProduceStatus().equals("1")) {
				row2.createCell(4).setCellValue("已做计划");
			} else if (cusOrderList.get(i).getProduceStatus().equals("2")) {
				row2.createCell(4).setCellValue("已排产");
			} else if (cusOrderList.get(i).getProduceStatus().equals("3")) {
				row2.createCell(4).setCellValue("生产中");
			} else {
				row2.createCell(4).setCellValue("已生产");
			}
			if (cusOrderList.get(i).getOutLibraryStatus().equals("0")) {
				row2.createCell(5).setCellValue("未出库");
			} else {
				row2.createCell(5).setCellValue("已出库");
			}
			if (cusOrderList.get(i).getOrderExamineStatus().equals("0")) {
				row2.createCell(6).setCellValue("未提交审核");
			} else if (cusOrderList.get(i).getOrderExamineStatus().equals("1")) {
				row2.createCell(6).setCellValue("审核中");
			} else {
				row2.createCell(6).setCellValue("审核通过");
			}
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(new Date());
		String fileName = nowtime+"销售计划表.xlsx";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    //关闭计划
    @RequestMapping("/closePlan")
    public @ResponseBody int closePlan(@RequestParam(value = "id") Integer id){
        int isSuccess = 0;
        isSuccess = customerOrderService.closePlan(id);
        return isSuccess;
    }

    //一下为修改状态的  审批流程 end
}
